package com.googleplus.ejb;

import java.io.ByteArrayInputStream;
import java.util.logging.Level;
import java.util.regex.Pattern;

import com.googleplus.GooglePlus;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.filter.ClientFilter;

public class GoogleJSONFilter extends ClientFilter {
	
	private static final Pattern pre = Pattern.compile("([\\[{,]),");
	private static final Pattern post = Pattern.compile(",([\\]},])");
	
	private static final String cleanJSON(String s){
		String result = s.substring(5);
		result = pre.matcher(result).replaceAll("$1null,");
		result = post.matcher(result).replaceAll(",null$1");
		// jason s was also un-escaping \\'s - what for?
		return result;
	}

	@Override
	public ClientResponse handle(ClientRequest req)
			throws ClientHandlerException {
		
        ClientResponse clientResponse = getNext().handle(req);
        
        String response = clientResponse.getEntity(String.class);
        GooglePlus.LOG.logp(Level.FINE, "GoogleJSONFilter", "handle", "Response before cleaning", response);
        
        response = cleanJSON(response);
        
        GooglePlus.LOG.logp(Level.FINE, "GoogleJSONFilter", "handle", "Response after cleaning", response);
        
        ByteArrayInputStream bais = new ByteArrayInputStream(response.getBytes());
        clientResponse.setEntityInputStream(bais);
        
        return clientResponse;
	}
	
	
	
	
}
